#!/bin/groovy
//设置流水线运行超时
timeout(time: 600, unit: 'SECONDS') {
    //mfs服务器地址
    MOOSEFS_MASTER="192.168.1.100"

    properties([
        buildDiscarder(logRotator(
                artifactDaysToKeepStr: '',
                artifactNumToKeepStr: '5',
                daysToKeepStr: '',
                numToKeepStr: '10'
                )),
        parameters([
            choice(
                name: "domain",
                choices: 'example.net',
                description: "选择需要签发的域名或者通配符域名"
            ),
            extendedChoice(
                name: "option",
                type: "PT_CHECKBOX",
                description: "是否强制，即证书未到期也强制签发,默认不勾选",
                quoteValue: false,
                saveJSONParameterToFile: false,
                value: "--force",
                descripttionPropertyValue: "--force",
                visibleItemCount: 1,
                multiSelectDelimiter: ',',
                defaultValue: ""
            )
        ]),
        pipelineTriggers([
            parameterizedCron("H 0 1 2,5,8,11 * %domain=example.net")
        ])
    ])

    try{
        node("cloud-server") {
            stage('证书检查') {
                sh "echo | openssl s_client -connect example.net:443 -servername example.net 2>/dev/null | openssl x509 -noout -dates"
            }
            stage('证书签发') {
                sh """
                    /root/.acme.sh/acme.sh \
                        --issue \
                        --server letsencrypt \
                        --dns dns_ali \
                        -d *.${params.domain} \
                        -d ${params.domain} \
                        ${params.option} && echo "证书已签发" || echo "证书未到期，禁止签发,强制签发请勾选--force"
                """
            }
            stage('更新公网证书'){
                sh """
                    /root/.acme.sh/acme.sh \
                        --installcert \
                        -d *.${params.domain} \
                        -d ${params.domain} \
                        --key-file /etc/nginx/ssl/STAR.example.net.key \
                        --fullchain-file /etc/nginx/ssl/STAR.example.net.pem \
                        --reloadcmd "systemctl reload nginx"
                """
                sh "echo | openssl s_client -connect example.net:443 -servername example.net 2>/dev/null | openssl x509 -noout -dates"
            }

            stage("证书归档"){
                dir("/etc/nginx/ssl") {
                    archiveArtifacts artifacts: "STAR.example.net.*", fingerprint: true
                    stash name: 'ssl', includes: "STAR.example.net.*"
                }
            }
        }
        stage('证书提交GITHUB仓库'){
            node('cloud-server') {
                dir("/data/workspace/github/cloud-ssl/nginx/ssl/") {
                    sh "cp /etc/nginx/ssl/* ."
                    sh "sudo -u leif git switch master"
                    sh "sudo -u leif git add STAR.example.net.* "
                    sh "sudo -u leif git commit -m 'update certificate' || echo '证书已是最新，无需提交'"
                    sh "sudo -u leif git push origin master"
                }
            }
        }
        stage('从GITHUB仓库拉取新证书并提交GITEA') {
            node('k8s-master-01'){
                dir("/data/workspace/github/example.net/cloud-ssl") {
                    sh "git switch master"
                    sh "git pull origin master"
                    sh "git push gitlab"
                    sh "rsync -avP nginx/ssl/* /data/workspace/github/devops/k8s-nginx/ssl/"
                }
                dir("/data/workspace/github/devops/k8s-nginx/ssl"){
                    sh "rsync -avP * root@${MOOSEFS_MASTER}::ssl/"
                    sh "git add STAR.example.net.* "
                    sh "git commit -m 'update certificate' || echo '证书已是最新，无需提交'"
                    sh "git push gitlab && git push"
                }
            }
        }
        stage('更新内网证书'){
           node('k8s-master-01') {
               dir('ssl') {
                   unstash "ssl"
                   namespaceArray = sh(returnStdout: true, script: "kubectl get ingress -A | grep github | awk '{print \$1}' | uniq").trim().split("\\s+")
                   println "用到证书的命名空间有：${namespaceArray}"
                   for (namespace in namespaceArray) {
                       println "删除${namespace}下的example-tls"
                       sh "kubectl delete secrets example-tls -n ${namespace}"
                       sh "kubectl create secret tls example-tls --key STAR.example.net.key --cert STAR.example.net.pem -n ${namespace} && echo 'example-tls在${namespace}上创建成功' || echo 'example-tls在${namespace}上创建失败'"
                   }
               }
           }
        }
        stage('自动触发Nginx重载任务') {
            build job: 'nginx_rsync_config_reload',parameters:[string(name: 'GIT_BRANCH',value: 'master')]
        }
    }
    catch(Exception e) {
        currentBuild.result = "FAILURE"
    }
    finally {
       def currResult = currentBuild.result ?: 'SUCCESS'
    }
}
